package com.example.administrator.myapplication.net.chain;

import com.example.administrator.myapplication.net.Call;
import com.example.administrator.myapplication.net.HttpClient;
import com.example.administrator.myapplication.net.HttpConnection;
import com.example.administrator.myapplication.net.Response;

import java.util.List;

public class InterceptorChain {
    List<Interceptor> interceptors;
    int index;
    Call call;
    HttpConnection connection;

    public InterceptorChain(List<Interceptor> interceptors, int index, Call call) {
        this.interceptors = interceptors;
        this.index = index;
        this.call = call;
    }

    public InterceptorChain(List<Interceptor> interceptors, int index, Call call, HttpConnection connection) {
        this.interceptors = interceptors;
        this.index = index;
        this.call = call;
        this.connection = connection;
    }

    public Response process(HttpConnection connection) throws Exception {
        this.connection = connection;
        return process();
    }

    public Response process() throws Exception {
        if (index >= interceptors.size()) {
            throw new IllegalStateException("chain out of bounds");
        }
        Interceptor interceptor = interceptors.get(index);
        InterceptorChain chain = new InterceptorChain(interceptors, index + 1, call, connection);
        Response response = interceptor.intercept(chain);

        return response;
    }
}
